﻿using Nemerle.Collections;
using Nemerle.Text;
using Nemerle.Utility;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.IO;
using System.Xml.Linq;
using Nemerle2.Compiler;

namespace DocBrowser
{
  /// <summary>
  /// Description of XmlDocRepository.
  /// </summary>
  class XmlDocRepository
  {
    _docs : IDictionary[Type, IDictionary[string, XElement]] = Dictionary.[Type, IDictionary[string, XElement]]();
    
    public this()
    {
    }
      
    public this(files : list[string])
    {
      files.Iter(LoadFile)
    }
      
    public LoadFile(fileName : string) : void 
    {
      unless (File.Exists(fileName))
        throw FileNotFoundException(fileName);
          
      def doc = XDocument.Load(fileName);
        
      foreach (node is XElement in doc.Root.Element("members").Nodes())
      {
        def memberName = node.Attribute("name").Value;
        
        match (memberName.Split(':').ToNList())
        {
          | ["T", name] => ();
            def key = typeof(ITypeInfo);
            unless (_docs.ContainsKey(key))
              _docs[key] = Dictionary();
            
            _docs[key].Add(name, node)
          | _ => 
            ();
        }
      }
    }
    
    public GetDoc(type : ITypeInfo) : option[XElement]
    {
      def typeName = if (type.TypeParams.Any())
        $"$(type.FullName)`$(type.TypeParams.Count())"
      else
        type.FullName;
        
      GetDoc(typeof(ITypeInfo), typeName)
    }
    
    public GetDoc(folder : Type, key : string) : option[XElement]
    {
      if (_docs.ContainsKey(folder) && _docs[folder].ContainsKey(key))
        Some(_docs[folder][key])
      else 
        None()
    }
  }
}
